package com.yff.tuan.controller;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yff.tuan.api.ApiResult;
import com.yff.tuan.api.Result;
import com.yff.tuan.model.CoCompanyExample;
import com.yff.tuan.model.CoFleet;
import com.yff.tuan.model.CoFleetExample;
import com.yff.tuan.model.CoFleetExample.Criteria;
import com.yff.tuan.service.CoCompanyService;
import com.yff.tuan.service.CoFleetService;


@Controller
@RequestMapping("/fleet")
public class FleetController {
	@Autowired CoFleetService coFleetService;
	@Autowired CoCompanyService coCompanyService;
	
	@RequestMapping("/query")
	public String query(Model model,HttpServletRequest request,HttpServletResponse response) {
		int role = (int) request.getSession().getAttribute("role");
		int userId = (int) request.getSession().getAttribute("userId");
		
		
		
		CoFleetExample example = new CoFleetExample();
		Criteria criteria = example.createCriteria();
		criteria.andCoUserIdEqualTo(userId);
		model.addAttribute("fleet", coFleetService.query(example));
		return "fleet";
	}
	
	@RequestMapping("/detail")
	public String detail(Model model,Integer id,HttpServletRequest request,HttpServletResponse response){
		if(null != id){
			model.addAttribute("fleet", coFleetService.findByPrimaryKey(id));
		}
		return "fleet_detail";
	}
	
	@RequestMapping("/toadd")
	public String toadd(Model model,Integer id,HttpServletRequest request,HttpServletResponse response){
		if(null != id){
			model.addAttribute("fleet", coFleetService.findByPrimaryKey(id));
		}
		model.addAttribute("companies",coCompanyService.query(new CoCompanyExample()));
		return "fleet_add";
	}
	
	@RequestMapping("/add")
	@ResponseBody
	public Object add(Model model,CoFleet coFleet,HttpServletRequest request,HttpServletResponse response){
		if(null == coFleet) {
			return ApiResult.ERROR(Result.INVALID_PARAMETERS);
		}
		int userId = (int) request.getSession().getAttribute("userId");
		coFleet.setCoUserId(userId);
		if(null  != coFleet.getId()){
			return ApiResult.SUCCESS(coFleetService.updateByPrimaryKey(coFleet));
		}else{
			return ApiResult.SUCCESS(coFleetService.insert(coFleet));
		}
	}
	
	@RequestMapping("/del")
	@ResponseBody
	public Object add(Model model,Integer id,HttpServletRequest request,HttpServletResponse response){
		if(null == id) {
			return ApiResult.ERROR(Result.INVALID_PARAMETERS);
		}
		return ApiResult.SUCCESS(coFleetService.delByPrimaryKey(id));
	}
}
